package org.travelfusion.xmlclient.ri.handler.misc;

import java.util.HashMap;
import java.util.Map;

import javax.xml.stream.XMLStreamConstants;

import org.travelfusion.xmlclient.handler.HandlesRequestsFor;
import org.travelfusion.xmlclient.impl.handler.AbstractXmlToolRequestStAXResponseHandler;
import org.travelfusion.xmlclient.ri.xobject.misc.XGetProductTypesRequest;
import org.travelfusion.xmlclient.ri.xobject.misc.XGetProductTypesResponse;

@HandlesRequestsFor(XGetProductTypesRequest.class)
public class GetProductTypesHandler extends AbstractXmlToolRequestStAXResponseHandler<XGetProductTypesRequest, XGetProductTypesResponse> {

	@Override
	protected void fillTemplate() throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public XGetProductTypesResponse handleResponse() throws Exception {

		Map<String, String> supplierTypes = new HashMap<String, String>();

		StringBuilder builder = new StringBuilder(32);

		String supplier = null;
		String type = null;
		String currentName = null;

		done : for (int event; ((event = responseReader.next()) != XMLStreamConstants.END_DOCUMENT);) {
			switch (event) {
				case XMLStreamConstants.START_ELEMENT :
					builder.setLength(0);
					currentName = responseReader.getName().getLocalPart();					
					break;
				case XMLStreamConstants.CHARACTERS :
					if (supplier == null || type == null) {
						builder.append(responseReader.getTextCharacters(), responseReader.getTextStart(), responseReader.getTextLength());
					}
					break;
				case XMLStreamConstants.END_ELEMENT :
					if (supplier == null || type == null) {
						currentName = responseReader.getName().getLocalPart();
					
						if ("Name".equals(currentName)) {
							supplier = builder.toString().trim();
						} else if ("ProductType".equals(currentName)) {
							type = builder.toString().trim();
							supplierTypes.put(supplier, type);
							supplier = null;
							type = null;
						}
					} else if ("AirlineList".equals(currentName)) {
						break done;
					}
					currentName = null;
					break;
			}
		}

		XGetProductTypesResponse response = new XGetProductTypesResponse();
		response.setSupplierTypes(supplierTypes);
		return response;
	}

}
